package com.mt.mtyx.common.auth;

import com.mt.mtyx.common.utils.JwtHelper;
import com.mt.mtyx.common.utils.RedisConst;
import com.mt.mtyx.vo.user.UserLoginVo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 *
 * @author WMT
 * @Date 2023/9/21 11:25
 */
public class UserLoginInterceptor implements HandlerInterceptor {

    private RedisTemplate<String, Object> redisTemplate;

    public UserLoginInterceptor(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler
    ) throws Exception {
        this.getUserLoginVo(request);
        return true;
    }


    /**
     * 从请求头中获取用户信息，并存到上下文中
     * @param request 请求头
     */
    private void getUserLoginVo(HttpServletRequest request) {
        // 1.从请求头获取token
        String token = request.getHeader("token");
        // 2.判断token是否为空
        if (!StringUtils.isEmpty(token)) {
            // 3.从token获取userId
            Long userId = JwtHelper.getUserId(token);
            // 4.根据userId从Redis中获取用户信息
            UserLoginVo userLoginVo = (UserLoginVo) redisTemplate
                    .opsForValue()
                    .get(RedisConst.USER_LOGIN_KEY_PREFIX + userId);
            if (userLoginVo != null) {
                // 5.把用户信息存到TreadLocal
                AuthContextHolder.setUserId(userId);
                AuthContextHolder.setWareId(userLoginVo.getWareId());
                AuthContextHolder.setUserLoginVo(userLoginVo);
            }
        }
    }
}
